<template>
  <view>
    <!-- 模块1：收货地址 -->
    <!-- 事件绑定给分区盒子，两种情况都给触发收货地址 -->
    <view @click="getUserAddress" class="address">
      <!-- 正常情况：显示收货地址 -->
      <view v-if="address.userName" class="address-info">
        <view class="address-detail">{{ addressDetail }}</view>
        <view class="address-user">
          {{ address.userName }} {{ address.telNumber }}
        </view>
      </view>
      <!-- 互斥情况：显示按钮 -->
      <view v-else class="address-btn">添加地址</view>
    </view>
    <!-- 模块2：已选商品列表 -->
    <view class="goods-list">
      <view class="goods-title">已选商品</view>
      <view
        class="cart-item"
        v-for="item in selectCartList"
        :key="item.goods_id"
      >
        <view class="cart-count"> x{{ item.goods_count }} </view>
        <navigator
          class="goods-item"
          :url="`/pages/goods_detail/goods_detail?goods_id=${item.goods_id}`"
          hover-class="none"
        >
          <!-- 商品图片 -->
          <image
            class="goods-image"
            :src="item.goods_small_logo || defaultImage"
            mode="scaleToFill"
          />
          <!-- 商品信息 -->
          <view class="goods-info">
            <view class="goods-name">{{ item.goods_name }}</view>
            <view class="goods-price">{{ item.goods_price }}</view>
          </view>
        </navigator>
      </view>
    </view>
    <!-- 模块3：底部操作栏 -->
    <view class="bottom-bar">
      <!-- 合计 -->
      <view class="total">
        <text class="total-name">合计：</text>
        <text class="total-price">{{ selectCartListPrice }}</text>
      </view>
      <!-- 结算 -->
      <view @click="handlerPay" class="account">
        去支付({{ selectCartListCount }})
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
import { userWxlogin } from "@/api/users";
import { ordersCreate, ordersPayInfo, ordersCheck } from "@/api/order";
export default {
  data() {
    return {
      // 收货地址
      address: {},
    };
  },
  computed: {
    // 省市区地址拼接
    addressDetail() {
      // 解构出需要拼接的字段
      const { provinceName, cityName, countyName, detailInfo } = this.address;
      // 返回拼接后的地址
      return [provinceName, cityName, countyName, detailInfo].join(" ");
    },
    // 映射 getters 到 computed 中
    ...mapGetters([
      "selectCartList",
      "selectCartListPrice",
      "selectCartListCount",
    ]),
  },
  methods: {
    async getUserAddress() {
      // ✅获取用户收货地址。调起用户编辑收货地址的原生界面
      // 🚨注意：该接口在 H5 端不支持，H5 端需要自己通过表单实现
      const [error, res] = await uni.chooseAddress();
      // 保存收货地址信息
      this.address = res;
    },
    // 🎯🎯🎯🎯去支付按钮 - 重点难点
    async handlerPay() {
      // 0. 用户收货地址
      if (!this.address.userName) {
        uni.showToast({ title: "请选择收货地址~", icon: "none" });
        return;
      }
      // 把登录流程封装成 action，再通过 dispatch 调用即可
      await this.$store.dispatch("userWxLogin");
      // 🚨🚨支付流程的步骤较多，工作的时候按流程图和后端接口逐个调用即可。
      // 🚨🚨流程较多的情况，求稳放到第一位，调一个接口就要打印检查，因为后面流程依赖前面流程的参数
      try {
        // 2. 获取自己后台返回的支付相关参数 - 🚨流程较多，按后端接口要求来操作
        //   2.1  创建订单，获取订单编号
        const ordersCreateRes = await ordersCreate({
          order_price: this.selectCartListPrice,
          consignee_addr: this.addressDetail,
          goods: this.selectCartList.map((item) => {
            return {
              goods_id: item.goods_id,
              goods_price: item.goods_price,
              goods_number: item.goods_count,
            };
          }),
        });
        // console.log('ordersCreateRes', ordersCreateRes)
        const { order_number } = ordersCreateRes.data.message;
        console.log("order_number", order_number);
        //   2.2  根据订单编号生成支付信息
        const payInfoRes = await ordersPayInfo(order_number);
        // console.log('payInfoRes', payInfoRes)
        const { pay } = payInfoRes.data.message;
        console.log("pay", pay);
        // 3. 调用微信接口实现 支付
        const { errMsg } = await wx.requestPayment(pay);
        console.log("errMsg", errMsg);
        // 4. 更新订单支付状态
        const ordersCheckRes = await ordersCheck(order_number);
        console.log("ordersCheckRes", ordersCheckRes);
        // 5. 跳转到订单页面
        uni.showToast({ title: "支付成功", icon: "success" });
      } catch (error) {
        console.log("发送给后端错误", error);
        uni.showToast({ title: "支付失败", icon: "error" });
      }
    },
  },
};
</script>

<style lang="scss">
page {
  background-color: #f9f9f9;
}
// 模块1：收货地址
.address {
  background-color: #fff;
  margin: 20rpx;
  padding: 20rpx;
  border-radius: 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  .address-info {
    width: 100%;
    .address-detail {
      font-size: 30rpx;
      font-weight: bold;
      margin-bottom: 20rpx;
    }
  }
  .address-btn {
    width: 303rpx;
    height: 90rpx;
    border-radius: 45rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border: 1px solid #eb4450;
    color: #eb4450;
  }
}

// 模块2：已选商品列表
.goods-list {
  background-color: #fff;
  margin: 20rpx;
  padding: 20rpx;
  border-radius: 10rpx;
  .goods-title {
    line-height: 40rpx;
    font-size: 26rpx;
  }
  .cart-item {
    position: relative;
    .cart-count {
      position: absolute;
      right: 20rpx;
      bottom: 30rpx;
    }
    // 选中最后一项
    &:last-child {
      .goods-item {
        border: none;
      }
    }
  }
}
</style>
